#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ == taoyulong2018@gmail.com
# __time__ == 2023/2/23 15:02
# ===========================================
#       题目名称： 15. 三数之和
#       题目地址： https://leetcode.cn/problems/3sum-closest/
#       题目描述： https://note.youdao.com/s/LWYgPSzT
# ===========================================


class Solution:

    def threeSumClosest(self, nums, target):
        if len(nums) < 3:
            return 0
        # 排序
        nums.sort()
        # 最小的值
        smallValue = nums[0] + nums[1] + nums[2]
        for i in range(len(nums)):
            # 左右指针
            left, right = i + 1, len(nums) - 1
            while left < right:
                result = nums[i] + nums[left] + nums[right]
                if abs(target - result) < abs(target - smallValue):
                    smallValue = result
                if result > target:
                    right -= 1
                elif result < target:
                    left += 1
                else:
                    return target
        return smallValue


if __name__ == "__main__":
    s = Solution()
    print("nums = [-1,2,1,-4], target = 1 =>" + str(s.threeSumClosest(nums=[-1, 2, 1, -4], target=1)))  # 2
    print("nums = [0,0,0], target = 1 =>" + str(s.threeSumClosest(nums=[0, 0, 0], target=1)))  # 0
